package org.ws.task.netty.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.ByteBuffer;

public class MessageDecoder extends LengthFieldBasedFrameDecoder {

    private static Logger log = LoggerFactory.getLogger(MessageDecoder.class.getName());

    public MessageDecoder(){
        super(Integer.MAX_VALUE,0,4,0,4);
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        ByteBuf frame = null;
        try {
            frame = (ByteBuf) super.decode(ctx, in);
            if (frame == null) {
                return null;
            }
            ByteBuffer byteBuffer = frame.nioBuffer();
            int length = byteBuffer.limit();
            int type = byteBuffer.getInt();
            byte[] data = new byte[length-4];
            byteBuffer.get(data);
            Class clazz = CodecUtil.getClass(type);
            if(clazz != null) {
                return CodecUtil.decode(data, clazz);
            }
            else {
                log.error("message type error:{}",type);
                return null;
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return null;
        }
        finally {
            if(frame != null){
                frame.release();
            }
        }
    }

}
